<template>
  <div class="sales_filing_container">
    <div class="first_wrap">
      <span style="margin-left: 0">月份</span>
      <el-select
        v-model="monthPullSelectValue"
        placeholder="请选择"
        clearable
        @clear="queryBtnClick"
      >
        <el-option
          v-for="item in monthPullSelectList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <span>营业员</span>
      <el-select
        v-model="assistantPullSelectValue"
        placeholder="请选择"
        clearable
        @clear="queryBtnClick"
      >
        <el-option
          v-for="item in assistantPullSelectList"
          :key="item.id"
          :label="item.personnelName"
          :value="item.personnelNo"
        >
        </el-option>
      </el-select>
      <span>开卡目标</span>
      <el-input v-model="openCardTargetInputvalue"></el-input>
      <span>销售目标</span>
      <el-input v-model="salesTargetInputValue"></el-input>
    </div>
    <!-- 第二行按钮容器 -->
    <div class="second_wrap">
      <el-button icon="el-icon-search" type="primary" @click="queryBtnClick"
        >查询</el-button
      >
      <el-button icon="el-icon-folder-checked" @click="keepBtnClick"
        >保存</el-button
      >
      <el-button icon="el-icon-delete" @click="deleteBtnClick">删除</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table_container">
      <el-table
        :data="tableData"
        style="width: 100%"
        :cell-style="{ padding: 0, height: '30px' }"
        :header-cell-style="{
          background: '#f4f4f4',
          padding: 0,
          height: '40px'
        }"
        height="65vh"
        highlight-current-row
        @row-click="handleTableRowClick"
      >
        <el-table-column prop="month" label="月份"> </el-table-column>
        <el-table-column prop="personnelNo" label="营业员编号">
        </el-table-column>
        <el-table-column prop="personnelName" label="营业员"> </el-table-column>
        <el-table-column prop="cardNumber" label="开卡目标" width="150">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.cardNumber"
              @change="tableInputChange(scope.row)"
              @keyup.enter.native="handleEnter($event)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="sellMoney" label="销售目标" width="150">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.sellMoney"
              @change="tableInputChange(scope.row)"
              @keyup.enter.native="handleEnter($event)"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          style="width: 100%"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paramsData.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="paramsData.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
// 导出月份数组
import { monthList_value_number } from '../../../../../config/base_data.js'
import { select } from '../../../../../network/customerOrderTotal.js'
// console.log(monthList, 'aa')
//查询VIP职员（营业员）
import { query_vip_personnel } from '../../../../../request/store/store_baseInfo_request.js'
//页面接口的引入
import {
  add_achievement_target_api,
  query_achievement_target_api,
  change_open_card_or_sales_target_api,
  delete_achievement_target_api
} from '../../../../../request/store/store_baseInfo_request.js'
export default {
  data() {
    return {
      // 表格的行被点击的时候，保存的id
      currentRowId: '',
      // 月份下拉框选中的值和数组
      monthPullSelectValue: '',
      monthPullSelectList: monthList_value_number,
      // 营业员下拉框选中的值和数组
      assistantPullSelectValue: '',
      assistantPullSelectList: '',
      // 开卡目标输入的值
      openCardTargetInputvalue: 3,
      // 销售目标输入的值
      salesTargetInputValue: '',
      // 表格数据
      tableData: [],

      // 以下新增
      paramsData: {
        month: '',
        personnelNo: '',
        page: 1,
        limit: 10
      },
      total: 0
    }
  },
  created() {
    // 获取营业员数据
    this.query_vip_personnel()
  },
  methods: {
    // 获取营业员数据
    async query_vip_personnel() {
      const { data: res } = await query_vip_personnel({
        directSaleNo: this.$store.state.currentStoreData.no
      })

      // console.log(res, 'directSaleNo')
      // 赋值给营业员数组
      this.assistantPullSelectList = res.data
    },
    // 保存按钮被点击的时候，触发的函数
    async keepBtnClick() {
      if (!this.monthPullSelectValue) return this.$message.warning('请选择月份')
      if (!this.assistantPullSelectValue)
        return this.$message.warning('请选择营业员')
      if (!this.openCardTargetInputvalue)
        return this.$message.warning('开卡目标不能为空')
      if (!this.salesTargetInputValue)
        return this.$message.warning('销售目标不能为空')
      // 拿到选中的营业员的营业编号（也是唯一的），然后去遍历数组，找到这个对象，在拼接后端需要的数据
      const currentSelectAssistant = this.assistantPullSelectList.find(
        (item) => {
          return item.personnelNo === this.assistantPullSelectValue
        }
      )
      console.log(currentSelectAssistant, 'currentSelectAssistant')
      // 新建vip直营目标业绩要的参数对象
      const buildParamsObj = {
        cardNumber: this.openCardTargetInputvalue, // 开卡目标
        directSaleNo: currentSelectAssistant.directSaleNo, // 直营店编号
        month: this.monthPullSelectValue, // 月份
        personnelName: currentSelectAssistant.personnelName, // 职员名称
        personnelNo: currentSelectAssistant.personnelNo, // 职员编号
        sellMoney: this.salesTargetInputValue, // 销售目标
        softwareCustomerId: currentSelectAssistant.softwareCustomerId, // 软件客户id
        status: currentSelectAssistant.status // 状态（0正常1禁用）
      }
      // console.log(buildParamsObj, 'buildParamsObj')
      const { data: res } = await add_achievement_target_api(buildParamsObj)
      // console.log(res, 'add_achievement_target_api')

      if (res.code === 200) {
        this.$message.success(res.msg)
        this.queryBtnClick()
        this.monthPullSelectValue = ''
        this.assistantPullSelectValue = ''
        this.openCardTargetInputvalue = ''
        this.salesTargetInputValue = ''
      } else {
        this.$message.error(res.msg)
      }

      // if (res.code !== 200) return this.$message.warning('保存失败，请稍后再试')
      // // 保存成功之后，要清除数据,这个要写在前，查询是这样的条件也可以的
      // this.monthPullSelectValue = ''
      // this.assistantPullSelectValue = ''
      // this.openCardTargetInputvalue = ''
      // this.salesTargetInputValue = ''
      // // 如果表格有数据的话，那么就更新列表，否则不要更新
      // if (this.tableData.length) {
      //   this.queryBtnClick()
      // }
      // // 保存成功
      // this.$message.success('保存成功')
    },
    // 查询按钮被点击的时候，触发的函数
    async queryBtnClick() {
      // 后端要的可以查询的数据
      const queryObj = {
        month: this.monthPullSelectValue,
        personnelNo: this.assistantPullSelectValue,
        // 新增
        page: this.paramsData.page,
        limit: this.paramsData.limit
      }
      const { data: res } = await query_achievement_target_api(queryObj)
      if (res.code === 200) {
        // console.log(res, 'query_achievement_target_api')
        // 赋值给表格数据
        this.tableData = res.data
        this.total = res.total
      }
    },
    //  表格中输入框的内容改变的时候/或者按下回车的时候，触发的函数
    async tableInputChange(row) {
      console.log('改变')
      const changeOpenCardOrSalesTargetParamsObj = {
        cardNumber: row.cardNumber, //开卡目标
        directSaleNo: row.directSaleNo, //直营店编号
        id: row.id, //id编号
        month: row.month, //月份（1-12 数字表示）
        personnelName: row.personnelName, //职员名称
        personnelNo: row.personnelNo, //职员编号
        sellMoney: row.sellMoney, //销售目标
        softwareCustomerId: row.softwareCustomerId, //软件客户id
        status: row.status //状态（0正常1禁用）
      }
      // 发起ajax请求,保存数据
      const { data: res } = await change_open_card_or_sales_target_api(
        changeOpenCardOrSalesTargetParamsObj
      )
      console.log(res, 'changeOpenCardOrSalesTargetParamsObj')
      if (!res || res.code !== 200) return
      // 成功之后，直接调用查询的方法，更新数据，这里不调用也行
      // this.queryBtnClick()
      this.$message.success('保存成功')
    },
    // 按下回车之后，触发的函数，直接失去焦点
    handleEnter(e) {
      // 按下回车的时候，失去焦点
      e.target.blur()
    },
    // 表格的行被点击的时候，触发的函数
    handleTableRowClick(row) {
      // 保存当前行的id
      this.currentRowId = row.id
    },
    // 删除按钮被点击的时候，触发的函数
    deleteBtnClick() {
      if (!this.currentRowId) return this.$message.warning('请选择要删除的数据')

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await delete_achievement_target_api(
            this.currentRowId
          )
          if (data.code === 200) {
            this.$message.success(data.msg)
            this.queryBtnClick()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /**
     * --------- 新增 ----------
     */
    async onSearch(params) {
      const { data } = await query_achievement_target_api(params)
      if (data && data.code === 200) {
        this.tableData = data.data
        this.total = data.total
      }
    },
    handleCurrentChange(value) {
      this.paramsData.month = this.monthPullSelectValue
      this.paramsData.personnelNo = this.assistantPullSelectValue
      this.paramsData.page = value
      this.onSearch(this.paramsData)
    },
    handleSizeChange(value) {
      this.paramsData.month = this.monthPullSelectValue
      this.paramsData.personnelNo = this.assistantPullSelectValue
      this.paramsData.limit = value
      this.onSearch(this.paramsData)
    }
  }
}
</script>

<style lang="less" scoped>
.first_wrap {
  span {
    margin-right: 8px;
    // 让所有的span都有这个left边距
    &:nth-child(2n - 1) {
      margin-left: 16px;
    }
  }
  .span_left_16px {
    margin-left: 16px;
  }
  // input输入框的样式
  /deep/.el-input {
    // 宽度生效
    width: 160px;
    height: 32px;
    .el-input__inner {
      height: 32px;
    }
  }
}
.second_wrap {
  margin-top: 16px;
}
.table_container {
  // 进入页面要刷新才有效果，是因为样式的问题
  height: 72vh;
  margin-top: 16px;
}
/deep/.el-input__icon {
  line-height: unset;
}
.pagination {
  margin-top: 10px;
  text-align: right;
  /deep/.el-input--suffix {
    .el-input__inner {
      width: 100px;
    }
  }
}
</style>
